package com.example.casesys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.casesys.dto.EvidDTO;
import com.example.casesys.entity.EvidInfo;
import com.example.casesys.mapper.EvidInfoMapper;
import com.example.casesys.service.EvidInfoService;
import com.example.casesys.utils.FileUtil;
import com.example.casesys.vo.Result;
import com.example.casesys.vo.ResultCodeEnum;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.example.casesys.utils.FileUrlPatterns.*;

/**
 * <p>
 * 证据信息表 服务实现类
 * </p>
 *
 * @author hongren
 * @since 2023-09-11
 */
@Service
public class EvidInfoServiceImpl extends ServiceImpl<EvidInfoMapper, EvidInfo> implements EvidInfoService {

    private static final Integer PAGE_SIZE = 10;
    @Resource
    private FileUtil fileUtil;
    @Resource
    private EvidInfoMapper evidInfoMapper;

    /**
     * 查询证据
     *
     * @param caseId 案件id
     * @return {@link Result}
     */
    @Override
    public Result selectEvid(String caseId, Integer pageId) {
        List<EvidInfo> infos;
        EvidDTO evidDTO = new EvidDTO();
        List<EvidInfo> evidInfos = new ArrayList<>();
        try {
            Page<EvidInfo> page = Page.of(pageId, PAGE_SIZE);
            QueryWrapper<EvidInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("case_id", caseId);
            wrapper.orderByDesc("evid_type","upload_time");
            Page<EvidInfo> infoPage = evidInfoMapper.selectPage(page, wrapper);
            infos = infoPage.getRecords();
            if (infos == null || infos.isEmpty()) {
                return Result.fail().message("没有证据信息!");
            }
            evidDTO.setCount(infoPage.getTotal());
        } catch (Exception e) {
            return Result.fail().message("查询失败！");
        }
//        数据库路径转移字符原因，更改客户端存放的路径
        for (EvidInfo evidInfo : infos) {
            String serName = evidInfo.getFileNameSer();
            String url = FILE_TO_DB_URL + serName;
            evidInfo.setFileNameSer(url);
            evidInfos.add(evidInfo);
        }
        evidDTO.setEvidList(evidInfos);
        return Result.ok(evidDTO).message("查询成功！");
    }

    /**
     * 添加证据
     *
     * @return {@link Result}
     */
    @Override
    public Result addEvid(EvidInfo evidInfo) {
        try {
            evidInfoMapper.insert(evidInfo);
            return Result.ok().message("证据添加成功");
        } catch (Exception e) {
            return Result.fail().message("添加失败！");
        }
    }

    /**
     * 更新证据
     *
     * @return {@link Result}
     */
    @Override
    public Result updateEvid(EvidInfo evidInfo) {
        try {
            if (updateById(evidInfo)) {
                return Result.ok().message("修改成功！");
            }
        } catch (Exception e) {
            return Result.fail().message("修改失败!");
        }
        return Result.fail().message("修改失败！");
    }

    /**
     * 删除证据
     *
     * @return {@link Result}
     */
    @Override
    public Result delEvid(Integer id) {
        try {
            EvidInfo evidInfo = evidInfoMapper.selectById(id);
            String fileNameSer = evidInfo.getFileNameSer();
            String path = FILE_URL_LINUX + fileNameSer;
            if (removeById(id)) {
//                删除证据文件
                fileUtil.delFile(path);
                return Result.ok().message("删除成功！");
            }
        } catch (Exception e) {
            return Result.fail().message("删除失败!");
        }
        return Result.fail().message("删除失败！");
    }

    /**
     * 上传文件信息
     *
     * @param file
     * @return
     */
    @Override
    public Result uploadFile(MultipartFile file) {

        Map<String, String> resMap = fileUtil.uploadFile(file);
        String url = resMap.get("url");
        if (url != null) {
            return Result.ok(url).message("文件上传成功");
        }
        return Result.fail().message(resMap.get("fail"));
    }

    /**
     * 修改文件信息
     *
     * @param id   证据id
     * @param file
     * @return
     */
    @Override
    public Result updateFile(Integer id, MultipartFile file) {
        EvidInfo evidInfo = evidInfoMapper.selectById(id);
        if (evidInfo == null) {
            return Result.fail().message("证据id不存在");
        }
        String ordNameSer = evidInfo.getFileNameSer();
        Map<String, String> resMap = fileUtil.uploadFile(file);
        evidInfo.setFileNameSer(resMap.get("serName"));
        evidInfo.setFileNameCli(resMap.get("cliName"));
        if (resMap.get("url") != null) {
            evidInfoMapper.updateById(evidInfo);
//            删除旧文件
            fileUtil.delFile(FILE_URL_LINUX + ordNameSer);
            return Result.ok(resMap.get("url")).message("文件修改成功");
        }
        return Result.fail().message(resMap.get("fail"));

    }

    /**
     * 文件下载
     *
     * @param serName 服务器中存的文件名
     * @return {@link ResponseEntity}<{@link byte[]}>
     */
    @Override
    public ResponseEntity<byte[]> downloadFile(String serName) {

//          判断数据库中是否存在该文件
        EvidInfo fileDB = evidInfoMapper.selectOne(new QueryWrapper<EvidInfo>().eq("file_name_ser", serName));
        if (fileDB == null) {
            return null;
        }
        return fileUtil.downloadFile(serName);
    }

}

